package com.kaisa.activity.fragment;

import android.annotation.TargetApi;
import android.content.Intent;
import android.graphics.drawable.AnimationDrawable;
import android.os.Build;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.MapStatus;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.MyLocationConfiguration;
import com.baidu.mapapi.map.MyLocationData;
import com.baidu.mapapi.model.LatLng;
import com.gc.flashview.FlashView;
import com.gc.flashview.constants.EffectConstants;
import com.gc.flashview.listener.FlashViewListener;
import com.handmark.pulltorefresh.library.ILoadingLayout;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.kaisa.activity.BaseApp;
import com.kaisa.activity.R;
import com.kaisa.activity.adapter.HomeAdapter;
import com.kaisa.activity.bean.HomeEntity;
import com.kaisa.activity.bean.MarketingActivities;
import com.kaisa.activity.constant.UrlHttp;
import com.kaisa.activity.ui.BuyActivity;
import com.kaisa.activity.ui.EnjoyHolidayActivity;
import com.kaisa.activity.ui.HomeTopActivity;
import com.kaisa.activity.ui.HotSellActivity;
import com.kaisa.activity.ui.LifeActivity;
import com.kaisa.activity.ui.MoreThemeActivity;
import com.kaisa.activity.ui.SearchCountriesActivity;
import com.kaisa.activity.ui.ShipActivity;
import com.kaisa.activity.ui.SortSearchActivity;
import com.kaisa.activity.ui.StartRoadActivity;

import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.view.annotation.ContentView;
import org.xutils.view.annotation.ViewInject;
import org.xutils.x;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by Administrator on 2015/12/12.
 * 首页
 */
@ContentView(R.layout.fragment_home)
public class HomeFragmeng extends BaseFragment implements View.OnClickListener {
    @ViewInject(R.id.ptr_list)
    private PullToRefreshListView pullToRefreshListView;
    private AnimationDrawable anima;
    private HomeAdapter adapter;
    private List<MarketingActivities.Position3Entity> list = new ArrayList<MarketingActivities.Position3Entity>();
    private ListView refreshableView;
    private View layout;
    private HomeEntity entity;
    // 声明地图的View
    @ViewInject(R.id.home_map)
    private MapView mMapView;
    private BaiduMap mBaiduMap;
    // 定位相关
    private LocationClient mLocationClient;
    private MyLocationListener myLocationListener = new MyLocationListener();
    private String address;

    public static HomeFragmeng newInstance() {
        HomeFragmeng fragment = new HomeFragmeng();
        return fragment;
    }

    private FlashView flashView;
    private ImageView hotImageView;
    private ImageView startImageView;
    private ImageView buyImageView;
    private ImageView holidayImageView;
    private ImageView nomanticImageView;
    private ImageView footImageView;
    private ImageView worldImageView;
    private TextView moreImageView;
    private Button searchButton;
    private TextView cityTextView;
    private boolean flag = false;

    @TargetApi(Build.VERSION_CODES.JELLY_BEAN)
    @Override
    public void initView() {
        mBaiduMap = mMapView.getMap();
        // 初始化LocationClient类
        mLocationClient = new LocationClient(getActivity().getApplicationContext());
        // 开启定位图层
        mBaiduMap.setMyLocationEnabled(true);
        // 初始化定位
        initLocation();
        // 设置数据接口回调
        mLocationClient.registerLocationListener(myLocationListener);
        // 开始定位
        mLocationClient.start();
        adapter = new HomeAdapter(list, getActivity());
        refreshableView = pullToRefreshListView.getRefreshableView();
        layout = LayoutInflater.from(getActivity()).inflate(R.layout.home_containts, null);
        AbsListView.LayoutParams params = new AbsListView.LayoutParams(
                AbsListView.LayoutParams.MATCH_PARENT, AbsListView.LayoutParams.WRAP_CONTENT);
        layout.setLayoutParams(params);
        refreshableView.addHeaderView(layout);
        flashView = (FlashView) layout.findViewById(R.id.flash_view);
        hotImageView = (ImageView) layout.findViewById(R.id.img_hotsell);
        startImageView = (ImageView) layout.findViewById(R.id.img_startroad);
        buyImageView = (ImageView) layout.findViewById(R.id.img_buy);
        holidayImageView = (ImageView) layout.findViewById(R.id.img_theme1);
        nomanticImageView = (ImageView) layout.findViewById(R.id.img_theme2);
        footImageView = (ImageView) layout.findViewById(R.id.img_theme3);
        worldImageView = (ImageView) layout.findViewById(R.id.img_theme4);
        moreImageView = (TextView) layout.findViewById(R.id.home_theme_more);
        searchButton = (Button) layout.findViewById(R.id.btn_search);
        cityTextView = (TextView) layout.findViewById(R.id.home_city);
        cityTextView.setText(address);
        moreImageView.setOnClickListener(this);
        hotImageView.setOnClickListener(this);
        startImageView.setOnClickListener(this);
        buyImageView.setOnClickListener(this);
        holidayImageView.setOnClickListener(this);
        nomanticImageView.setOnClickListener(this);
        footImageView.setOnClickListener(this);
        worldImageView.setOnClickListener(this);
        searchButton.setOnClickListener(this);
        pullToRefreshListView.setAdapter(adapter);
        pullToRefreshListView.setMode(PullToRefreshBase.Mode.PULL_FROM_START);
        pullToRefreshListView.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2<ListView>() {
            @Override
            public void onPullDownToRefresh(PullToRefreshBase<ListView> pullToRefreshBase) {
                list.clear();
                initData();
            }

            @Override
            public void onPullUpToRefresh(PullToRefreshBase<ListView> pullToRefreshBase) {

            }
        });
        ILoadingLayout loadingLayoutProxy = pullToRefreshListView.getLoadingLayoutProxy(true, false);
        ImageView img = new ImageView(getActivity());
        img.setBackground(getResources().getDrawable(R.drawable.refeshanimo));
        if (img.getBackground() instanceof AnimationDrawable) {
            anima = (AnimationDrawable) img.getBackground();
        }
        if (anima != null) {
            anima.start();
        }
        loadingLayoutProxy.setLoadingDrawable(img.getBackground());
        loadingLayoutProxy.setRefreshingLabel("下拉刷新...");
        loadingLayoutProxy.setReleaseLabel("正在加载...");
    }

    private void initLocation() {
        LocationClientOption clientOption = new LocationClientOption();
        clientOption.setOpenGps(true);
        clientOption.setIsNeedAddress(true);
        clientOption.setCoorType("bd09ll");
        clientOption.setLocationMode(LocationClientOption.LocationMode.Hight_Accuracy);// 设置定模式 高精度
        clientOption.setScanSpan(2000);// 设置两秒定位一次
    }

    @Override
    public void initData() {
        final RequestParams params = new RequestParams(UrlHttp.PATH_HOME);
        x.http().get(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String s) {
                pullToRefreshListView.onRefreshComplete();
                entity = JSON.parseObject(s, HomeEntity.class);
                list.addAll(entity.getMarketingActivities().getPosition3());
                List<String> imgs = new ArrayList<String>();
                for (int i = 0; i < entity.getTopPage().getActivityInfo().size(); i++) {
                    imgs.add(entity.getTopPage().getActivityInfo().get(i).getActPicUrl());
                }
                flashView.setImageUris(imgs);
                flashView.setEffect(EffectConstants.DEFAULT_EFFECT);
                x.image().bind(hotImageView, entity.getMarketingActivities().getPosition5().get(0).getPic());
                x.image().bind(startImageView, entity.getMarketingActivities().getPosition4().get(0).getPic());
                x.image().bind(buyImageView, entity.getMarketingActivities().getPosition6().get(0).getPic());
                x.image().bind(holidayImageView, entity.getMarketingActivities().getPosition1().get(0).getPic());
                x.image().bind(nomanticImageView, entity.getMarketingActivities().getPosition1().get(1).getPic());
                x.image().bind(footImageView, entity.getMarketingActivities().getPosition1().get(2).getPic());
                x.image().bind(worldImageView, entity.getMarketingActivities().getPosition1().get(3).getPic());
                adapter.notifyDataSetChanged();
            }

            @Override
            public void onError(Throwable throwable, boolean b) {

            }

            @Override
            public void onCancelled(CancelledException e) {

            }

            @Override
            public void onFinished() {

            }
        });
        flashView.setOnPageClickListener(new FlashViewListener() {
            @Override
            public void onClick(int position) {
                Intent intent = new Intent(getActivity(), HomeTopActivity.class);
                Bundle bundle = new Bundle();
                bundle.putSerializable("ben", entity);
                intent.putExtras(bundle);
                intent.putExtra("position", position);
                startActivity(intent);
            }
        });
        refreshableView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Intent intents = new Intent(getActivity(), LifeActivity.class);
                intents.putExtra("title", entity.getMarketingActivities().getPosition3().get(position - 2).getHeading());
                intents.putExtra("url", entity.getMarketingActivities().getPosition3().get(position - 2).getAddress());
                startActivity(intents);
            }
        });
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.home_theme_more:
                Intent moreTheme = new Intent(getActivity(), MoreThemeActivity.class);
                Bundle bundle = new Bundle();
                bundle.putSerializable("entity", entity);
                moreTheme.putExtras(bundle);
                startActivity(moreTheme);
                break;
            case R.id.img_hotsell:
                Intent hotSell = new Intent(getActivity(), HotSellActivity.class);
                hotSell.putExtra("title", entity.getMarketingActivities().getPosition5().get(0).getHeading());
                hotSell.putExtra("url",entity.getMarketingActivities().getPosition5().get(0).getAddress());
                startActivity(hotSell);
                break;
            case R.id.img_startroad:
                Intent startroad = new Intent(getActivity(), StartRoadActivity.class);
                startroad.putExtra("title", entity.getMarketingActivities().getPosition4().get(0).getHeading());
                startroad.putExtra("url", entity.getMarketingActivities().getPosition4().get(0).getAddress());
                startActivity(startroad);
                break;
            case R.id.img_buy:
                Intent buy = new Intent(getActivity(), BuyActivity.class);
                buy.putExtra("title", entity.getMarketingActivities().getPosition4().get(0).getHeading());
                startActivity(buy);
                break;
            case R.id.img_theme1://渡假界面
                Intent intent = new Intent(getActivity(), EnjoyHolidayActivity.class);
                startActivity(intent);
                break;
            case R.id.img_theme2:
                Intent intentship = new Intent(getActivity(), ShipActivity.class);
                startActivity(intentship);
                break;
            case R.id.img_theme3:
                Intent intents = new Intent(getActivity(), LifeActivity.class);
                intents.putExtra("title", entity.getMarketingActivities().getPosition1().get(2).getHeading());
                intents.putExtra("url", entity.getMarketingActivities().getPosition1().get(2).getAddress());
                startActivity(intents);
                break;
            case R.id.img_theme4:
                Intent intentss = new Intent(getActivity(), LifeActivity.class);
                intentss.putExtra("title", entity.getMarketingActivities().getPosition1().get(3).getHeading());
                intentss.putExtra("url", entity.getMarketingActivities().getPosition1().get(3).getAddress());
                startActivity(intentss);
                break;
            case R.id.btn_search:
                Intent search = new Intent(getActivity(), SortSearchActivity.class);
                startActivity(search);
                break;
        }
    }

    class MyLocationListener implements BDLocationListener {
        @Override
        public void onReceiveLocation(BDLocation location) {
            address = location.getAddrStr();
            double latitude = location.getLatitude();
            mBaiduMap.setMyLocationData(new MyLocationData.Builder().latitude(location.getLatitude())
                    .longitude(location.getLongitude()).build());
            // 改变地图的状态
            MapStatus status = new MapStatus.Builder()
                    .target(new LatLng(location.getLatitude(), location.getLongitude())).zoom(17).build();
            mBaiduMap.setMapStatus(MapStatusUpdateFactory.newMapStatus(status));
        }

    }

    @Override
    public void onResume() {
        super.onResume();
        mMapView.onResume();
    }

    @Override
    public void onPause() {
        mLocationClient.stop();
        mMapView.onPause();
        super.onPause();
    }

    @Override
    public void onDestroy() {
        mLocationClient.stop();
        mMapView.onDestroy();
        super.onDestroy();
    }
}
